<?php
/**
 * NOTE: Now POC research only;
 * used for requirements and kernel features research;
 * by xx;
 */

/**
 * Dwr Class
 * Dwr.php
 */
class Dwr {

	var $funcs = array();
	var $func_tmpl = "function #name(){return dwr.call('#name', arguments);}\n";
	var $buf = '';

	function __construct() {
	}

	function getInterface() {
		$json2js = file_get_contents('json2.js');
		$dwrjs = file_get_contents('dwr.js');
		$samplejs = file_get_contents('sample.js');
		$jsfuncs = '';
		foreach($this->funcs as $func) {
			$jsfuncs .= str_replace('#name', $func, $this->func_tmpl);
		}
		$this->buf = $jsfuncs . $dwrjs . $json2js . $samplejs;
	}

	function register($func) {
		return array_push($this->funcs, $func);
	}

	/**
	 * call
	 * call registered common php function with parameters;
	 */
	function call($func, $param) {
		$this->buf = json_encode(array('status' => 'ok', 'resp' => call_user_func_array($func, $param)));
	}

	/**
	 * listen
	 * invoke reverseAjax function;
	 */
	function listen($func, $param) {
	}

	/**
	 * output
	 * basic output handler;
	 */
	function output() {
		echo $this->buf;
	}
}

/**
 * User defined functions start here;
 * app.php
 */

/**
 * getTime
 * sample function 1
 */
function getTime() {
	return time;
}

/**
 * helloDwr
 * sample function 2
 * @param name {string} greeting name form client side;
 * @return {string}
 */
function helloDwr($name) {
	return "hello, $name!";
}

$task = $_REQUEST['task'];
$func = $_REQUEST['func'];

$param = json_decode(get_magic_quotes_gpc() ? stripslashes($_REQUEST['param']) : $_REQUEST['param']);

$dwr = new Dwr();

$dwr->register('getTime');
$dwr->register('reverse');
$dwr->register('helloDwr');


/**
 * frameword code
 * should be invoked by some method like dwr->exec();
 * Dwr.php
 */
switch ($task) {
case 'interface':
	$dwr->getInterface();
	break;
case 'call':
	$dwr->call($func, $param);
	break;
case 'listen':
	$dwr->listen($func, $param);
	break;
default:
	break;
}

$dwr->output();
?>
